package com.rd.student.jike.class2.lihongming.week724_730.Day724;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther:Heinrich
 * @Date:2023/7/24-07-24-15:00
 * @Description:com.rd.student.jike.class2.lihongming.Day0724
 * @version:1.0
 */
public class TestCyclicBarrier {
    //一定数量的线程 反复在栅栏处集合 当所有线程到达栅栏的位置 栅栏打开
    //等待过程中使用await()方法阻塞
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("全部到达，开始点餐");
                //关闭线程池
                service.shutdown();
            }
        });
        for (int i = 0; i < 5; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(new Random().nextInt(2000));
                        System.out.println(Thread.currentThread().getName() +
                                " 到达饭馆");
                        cyclicBarrier.await();
                    } catch (InterruptedException | BrokenBarrierException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}
